package com.xdf.teacher.activity;

import android.Manifest;
import android.app.Activity;

import net.neiquan.applibrary.wight.AlertDialog;
import net.neiquan.okhttp.NetCallBack;
import net.neiquan.okhttp.ResultModel;

import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.xdf.teacher.R;
import com.xdf.teacher.appliction.MyApplication;
import com.xdf.teacher.broadcasts.NetBroadcastReceiver;
import com.xdf.teacher.constant.RpcConstant;
import com.xdf.teacher.entity.RoomAttribute;
import com.xdf.teacher.entity.RoomList;
import com.xdf.teacher.entity.User;
import com.xdf.teacher.entity.UserBean;
import com.xdf.teacher.event.EventBuss;
import com.xdf.teacher.http.NetUtils;
import com.xdf.teacher.interfaces.NetEvent;
import com.xdf.teacher.utils.AudioUtil;
import com.xdf.teacher.utils.BukaHelper;

import org.greenrobot.eventbus.EventBus;
import org.haitao.common.utils.AppLog;
import org.haitao.common.utils.PixelUtil;
import org.haitao.common.utils.ToastUtil;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import tv.buka.sdk.BukaSDKManager;
import tv.buka.sdk.entity.Rpc;
import tv.buka.sdk.entity.Status;

/**
 * Created by JavaDog on 2018-3-21.
 */

public class ChatRoomActivity extends Activity implements NetEvent {
    @InjectView(R.id.mFrameLayout)
    FrameLayout mFrameLayout;
    @InjectView(R.id.stream_frame)
    FrameLayout stream_frame;
    @InjectView(R.id.stream_layout)
    LinearLayout stream_layout;
    @InjectView(R.id.stream_layout_)
    LinearLayout stream_layout_;
    @InjectView(R.id.mBootomLL)
    LinearLayout mBootomLL;
    @InjectView(R.id.mTeacherName)
    TextView mTeacherName;
    @InjectView(R.id.mVideoLogo)
    ImageView mVideoLogo;
    @InjectView(R.id.mVoiceLogo)
    ImageView mVoiceLogo;
    @InjectView(R.id.mListenLogo)
    ImageView mListenLogo;
    @InjectView(R.id.mSeeLogo)
    ImageView mSeeLogo;
    @InjectView(R.id.mExitLogo)
    ImageView mExitLogo;
    private BukaHelper bukaHelper;
    private AudioUtil audioUtil;
    private RoomList.DataBean dataBean;
    private int room_mute = -1;
    private int rec_all = -1;
    private int aid = -1;
    private int vid = -1;
    private int person_mute = -1;
    private int person_video = -1;
    private boolean videoFlag = false;
    private boolean voiceFlag = false;
    private boolean listenFlag = true;
    private boolean seeFlag = false;
    /**
     * 网络状态
     */
    private int netMobile;
    /**
     * 监控网络的广播
     */
    private NetBroadcastReceiver netBroadcastReceiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_chat_room);
        ButterKnife.inject(this);
        requestPermisson();
        audioUtil = AudioUtil.getInstance(this);
        bukaHelper = BukaHelper.getInstance(ChatRoomActivity.this);
        if (getIntent() != null) {
            dataBean = ((RoomList.DataBean) getIntent().getSerializableExtra("dataBean"));
            mTeacherName.setText(dataBean.getTeacher_name());
            AppLog.e("===========dataBean===========" + dataBean);
            initLive();
        }
        initListener();
    }

    private void initListener() {
        bukaHelper.setOnLoginListener(new BukaHelper.OnLoginListener() {
            @Override
            public void onStatusListener(int type, String str) {
                AppLog.e(type + "============onStatusListener==================" + str);
                switch (type) {
                    case 0:
                    case 1:
                        ToastUtil.shortShowToast(str);
                        bukaHelper.exit(stream_layout, stream_layout_);
                        finish();
                        break;
                    case 3:
                        ToastUtil.shortShowToast(str);
                        bukaHelper.exit(stream_layout, stream_layout_);
                        EventBus.getDefault().post(new EventBuss(EventBuss.EXIT_ROOM));
                        finish();
                        break;
                    case 4:
//                        ToastUtil.shortShowToast(str);
//                        bukaHelper.exit(stream_layout, stream_layout_);
//                        EventBus.getDefault().post(new EventBuss(EventBuss.EXIT_ROOM));
//                        finish();
                        break;
                }
            }
        });
        bukaHelper.setOnStatusListener(new BukaHelper.OnStatusListener() {
            @Override
            public void onStatusListener(int type, Status status) {
                AppLog.e("==========onStatusListener=============" + status.getStatus_extend());
                if (bukaHelper.getSessionUser(status.getSession_id()).getRole() == 1) {
                    switch (type) {
                        case 1:
                            bukaHelper.stopPlay_(status, stream_layout);
                            break;
                        case 2:
                            bukaHelper.play_(status, stream_layout);
                            break;
                    }
                }else{
                    switch (type) {
                        case 1:
                            bukaHelper.stopPlay2_(status);
                            break;
                        case 2:
                            if(!TextUtils.equals(status.getSession_id(),bukaHelper.getCurrentUser().getSession_id())) {
                                bukaHelper.play(status);
                            }
                            break;
                    }
                }
            }
        });
        bukaHelper.setOnRpcListener(new BukaHelper.OnRpcListener() {
            @Override
            public void onRpcListener(Rpc rpc) {
                UserBean currentUser = bukaHelper.getCurrentUser();
                AppLog.e(currentUser.getSession_id() + "=======rpc============" + rpc.getMessage());
                AppLog.e("=======currentUser111============" + currentUser.toString());
                if (rpc.getType() == RpcConstant.EXIT_ROOM) {//移除房间，点播
                    if (TextUtils.equals(currentUser.getSession_id(), rpc.getMessage())) {
                        bukaHelper.exit(stream_layout, stream_layout_);
                        finish();
                    }
                } else if (rpc.getType() == RpcConstant.START_RECORD) {//开始录制

                } else if (rpc.getType() == RpcConstant.END_RECORD) {//停止录制

                } else if (rpc.getType() == RpcConstant.ALL_MUTE) {//json，mute_all，1为静音，0为取消
                    String message = rpc.getMessage();
                    if (!TextUtils.isEmpty(message)) {
                        try {
                            JSONObject jsonObject = new JSONObject(message);
                            int mute_all = jsonObject.getInt("mute_all");
                            UserBean.PrivilegeBean privilegeBean = currentUser.getPrivilege();
                            voiceFlag = mute_all == 0 ? true : false;
                            if(privilegeBean.getPerson_video()==1){
                                voiceFlag=false;
                                mute_all=1;
                            }
                            setSpeakMute();
                            privilegeBean.setPerson_mute(mute_all);
                            privilegeBean.setPerson_video(privilegeBean.getPerson_video());
                            currentUser.setPrivilege(privilegeBean);
                            bukaHelper.setUserBean(currentUser);
                            bukaHelper.updateUser(currentUser);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        bukaHelper.setOnUserListener(new BukaHelper.OnUserListener() {
            @Override
            public void onUserListener(tv.buka.sdk.entity.User oldUser, tv.buka.sdk.entity.User user) {
                UserBean currentUser = bukaHelper.getCurrentUser();
                if (TextUtils.equals(user.getSession_id(), currentUser.getSession_id())) {
                    AppLog.e(oldUser.getUser_extend() + "=========onUserListener=============" + user.getUser_extend());
                    AppLog.e("=======currentUser222============" + currentUser.toString());
                    try {
                        JSONObject jsonObject = new JSONObject(user.getUser_extend());
                        JSONObject privilege = jsonObject.getJSONObject("privilege");
                        UserBean.PrivilegeBean privilegeBean = currentUser.getPrivilege();
                        if (privilege.has("person_mute")) {
                            person_mute = privilege.getInt("person_mute");
                            if (person_mute != -1) {
                                voiceFlag = person_mute == 0 ? true : false;
                                setSpeakMute();
                                privilegeBean.setPerson_video(privilegeBean.getPerson_video());
                                privilegeBean.setPerson_mute(person_mute);
                            }
                        }
                        if (privilege.has("person_video")) {
                            person_video = privilege.getInt("person_video");
                            if (person_video != -1) {
                                videoFlag = person_video == 0 ? true : false;
                                mVideoLogo.setImageResource(videoFlag ? R.drawable.video : R.drawable.video_not);
                                if (person_video == 0) {
                                    if (bukaHelper.getStatus() == null) {
                                        bukaHelper.publish(stream_layout_);
                                    }
                                } else {
                                    privilegeBean.setPerson_mute(1);
                                    voiceFlag = false;
                                    setSpeakMute();
                                    if (bukaHelper.getStatus() != null) {
                                        bukaHelper.stopPublish(stream_layout_);
                                    }
                                }
                                privilegeBean.setPerson_video(person_video);
                                privilegeBean.setPerson_mute(privilegeBean.getPerson_mute());
                            }
                        }
                        currentUser.setPrivilege(privilegeBean);
                        bukaHelper.setUserBean(currentUser);
                        bukaHelper.updateUser(currentUser);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void initLive() {
        User user = MyApplication.getInstance().user;
        final User.ResultBean result = user.getResult();
        NetUtils.getInstance().roomAttribute(result.getId(), dataBean.getRoom_id(), new NetCallBack() {
            @Override
            public void onSuccess(final String response, String mssage, ResultModel model) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        RoomAttribute roomAttribute = (RoomAttribute) JSON.parseObject(response, RoomAttribute.class);
                        UserBean userBean = new UserBean();
                        if (roomAttribute != null) {
                            List<String> courseExtend = roomAttribute.getCourseExtend();
                            if (courseExtend != null && courseExtend.size() > 0) {
                                for (int i = 0; i < courseExtend.size(); i++) {
                                    Map maps = (Map) JSON.parse(courseExtend.get(i));
                                    for (Object map : maps.entrySet()) {
                                        AppLog.e("========key=========" + ((Map.Entry) map).getKey() + "========value=======" + ((Map.Entry) map).getValue());
                                        if (((Map.Entry) map).getKey() == "room_mute") {
                                            room_mute = (int) ((Map.Entry) map).getValue();
                                        }
                                        if (((Map.Entry) map).getKey() == "rec_all") {
                                            rec_all = (int) ((Map.Entry) map).getValue();
                                        }
                                        if (((Map.Entry) map).getKey() == "aid") {
                                            aid = (int) ((Map.Entry) map).getValue();
                                        }
                                        if (((Map.Entry) map).getKey() == "vid") {
                                            vid = (int) ((Map.Entry) map).getValue();
                                        }
                                    }
                                }
                            }
                        }
                        userBean.setUser_id(result.getId());
                        userBean.setLogin_id(result.getId());
                        userBean.setCourse_id(dataBean.getRoom_id());
                        userBean.setRoom_mute(room_mute);
                        userBean.setRec_all(rec_all);
                        userBean.setAid(aid);
                        userBean.setVid(vid);
                        userBean.setUser_nickname(result.getNick_name());
                        userBean.setRole(result.getRole());
                        UserBean.PrivilegeBean privilege = new UserBean.PrivilegeBean();
                        privilege.setPerson_video(1);
                        privilege.setPerson_mute(1);
                        userBean.setPrivilege(privilege);
                        bukaHelper.initBukaViews(userBean, stream_layout);
                    }
                });
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {

            }
        }, RoomAttribute.class);
    }

    @OnClick({R.id.mVideoLogo, R.id.mVoiceLogo, R.id.mListenLogo, R.id.mSeeLogo, R.id.mExitLogo, R.id.mFrameLayout})
    public void onViewClicked(View view) {
        UserBean currentUser = bukaHelper.getCurrentUser();
        UserBean.PrivilegeBean privilegeBean = currentUser.getPrivilege();
        switch (view.getId()) {
            case R.id.mVideoLogo:
                videoFlag = !videoFlag;
                mVideoLogo.setImageResource(videoFlag ? R.drawable.video : R.drawable.video_not);
                if (videoFlag) {
                    if (bukaHelper.getStatus() == null) {
                        ToastUtil.shortShowToast("开启摄像头!");
                        bukaHelper.publish(stream_layout_);
                        seeFlag = true;
                        mSeeLogo.setImageResource(seeFlag ? R.drawable.see : R.drawable.see_not);
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
                        params.height = PixelUtil.dp2px(ChatRoomActivity.this, 200);
                        params.width = 0;
                        stream_frame.setLayoutParams(params);
                        mBootomLL.setVisibility(View.VISIBLE);
                        mTeacherName.setVisibility(View.VISIBLE);
                    }
                } else {
                    privilegeBean.setPerson_mute(1);
                    voiceFlag = false;
                    setSpeakMute();
                    if (bukaHelper.getStatus() != null) {
                        ToastUtil.shortShowToast("关闭摄像头!");
                        bukaHelper.stopPublish(stream_layout_);
                    }
                }
                privilegeBean.setPerson_video(videoFlag ? 0 : 1);
                privilegeBean.setPerson_mute(privilegeBean.getPerson_mute());
                currentUser.setPrivilege(privilegeBean);
                bukaHelper.setUserBean(currentUser);
                bukaHelper.updateUser(currentUser);
                break;
            case R.id.mVoiceLogo:
                if (bukaHelper.getStatus() != null) {
                    voiceFlag = !voiceFlag;
                    ToastUtil.shortShowToast(voiceFlag ? "打开麦克风！" : "关闭麦克风！");
                    setSpeakMute();
                } else {
                    ToastUtil.shortShowToast("请先开启摄像头!");
                }
                privilegeBean.setPerson_mute(voiceFlag ? 0 : 1);
                privilegeBean.setPerson_video(privilegeBean.getPerson_video());
                currentUser.setPrivilege(privilegeBean);
                bukaHelper.setUserBean(currentUser);
                bukaHelper.updateUser(currentUser);
                break;
            case R.id.mListenLogo:
                listenFlag = !listenFlag;
                ToastUtil.shortShowToast(listenFlag ? "打开扬声器！" : "关闭扬声器！");
                mListenLogo.setImageResource(listenFlag ? R.drawable.listen : R.drawable.listen_not);
                bukaHelper.play2_(!listenFlag);
//                setRoomMute();
                break;
            case R.id.mSeeLogo:
                seeFlag = !seeFlag;
                mSeeLogo.setImageResource(seeFlag ? R.drawable.see : R.drawable.see_not);
                if (seeFlag) {
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
                    params.height = PixelUtil.dp2px(ChatRoomActivity.this, 200);
                    params.width = 0;
                    stream_frame.setLayoutParams(params);
                    mBootomLL.setVisibility(View.VISIBLE);
                    mTeacherName.setVisibility(View.VISIBLE);
                } else {
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    stream_frame.setLayoutParams(params);
                    mTeacherName.setVisibility(View.GONE);
                    mBootomLL.setVisibility(View.GONE);
                }
                break;
            case R.id.mExitLogo:
                new AlertDialog.Builder(ChatRoomActivity.this).setTitle("是否确认退出?")
                        .setPositiveButton("退出", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                bukaHelper.exit(stream_layout, stream_layout_);
                                dialog.dismiss();
                                finish();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
                break;
            case R.id.mFrameLayout:
                if (mBootomLL.getVisibility() == View.VISIBLE) {
                    mBootomLL.setVisibility(View.GONE);
                    mTeacherName.setVisibility(View.GONE);
                } else {
                    mBootomLL.setVisibility(View.VISIBLE);
                    mTeacherName.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    private void setSpeakMute() {
        mVoiceLogo.setImageResource(voiceFlag ? R.drawable.voice : R.drawable.voice_not);
        if (bukaHelper.getStatus() != null) {
            BukaSDKManager.getMediaManager().setInputMute(bukaHelper.getStatus(), !voiceFlag);
        }
    }

    private void setRoomMute() {
        mListenLogo.setImageResource(listenFlag ? R.drawable.listen : R.drawable.listen_not);
        audioUtil.setSystemVolume(listenFlag ? audioUtil.getSystemMaxVolume() : 0);
        audioUtil.setMediaVolume(listenFlag ? audioUtil.getMediaMaxVolume() : 0);
        audioUtil.setAlarmVolume(listenFlag ? audioUtil.getAlermMaxVolume() : 0);
        audioUtil.setCallVolume(listenFlag ? audioUtil.getCallMaxVolume() : 0);
        audioUtil.setRingVolume(listenFlag ? audioUtil.getRingMaxVolume() : 0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private long exitTime = 0;

    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出直播间",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            bukaHelper.exit(stream_layout, stream_layout_);
            finish();
        }
    }

    private void requestPermisson() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionList = new ArrayList<>();
            if (this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (this.checkSelfPermission(Manifest.permission.CALL_PHONE)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.CALL_PHONE);
            }
            if (this.checkSelfPermission(Manifest.permission.READ_LOGS)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.READ_LOGS);
            }
            if (this.checkSelfPermission(Manifest.permission.READ_PHONE_STATE)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (this.checkSelfPermission(Manifest.permission.SET_DEBUG_APP)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.SET_DEBUG_APP);
            }
            if (this.checkSelfPermission(Manifest.permission.SYSTEM_ALERT_WINDOW)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.SYSTEM_ALERT_WINDOW);
            }
            if (this.checkSelfPermission(Manifest.permission.GET_ACCOUNTS)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.GET_ACCOUNTS);
            }
            if (this.checkSelfPermission(Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.CAMERA);
            }
            if (this.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.RECORD_AUDIO);
            }
            if (this.checkSelfPermission(Manifest.permission.MODIFY_AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.MODIFY_AUDIO_SETTINGS);
            }
            ActivityCompat.requestPermissions(this, permissionList.toArray(new String[permissionList.size()]), 100);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 100 && grantResults.length > 0) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
//                    Toast.makeText(this, permissions[i] + "，权限被用户拒绝了，可去手机设置里面修改。", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //注册广播
        if (netBroadcastReceiver == null) {
            netBroadcastReceiver = new NetBroadcastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(netBroadcastReceiver, filter);
            /**
             * 设置监听
             */
            netBroadcastReceiver.setNetEvent(this);
        }
    }

    @Override
    public void onNetChange(int netMobile) {
        this.netMobile = netMobile;
        isNetConnect();
    }

    private void isNetConnect() {
        AppLog.e("==============isNetConnect=============" + netMobile);
        switch (netMobile) {
            case 1://wifi

                break;
            case 0://移动数据

                break;
            case -1://没有网络

                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (netBroadcastReceiver != null) {
            //注销广播
            unregisterReceiver(netBroadcastReceiver);
        }
    }
}
